<template>
  <div>
    <el-row style="margin-top:20px;margin-left:80px">
      <el-button class="right" type="primary" @click="showAddDialog">添加</el-button>
      <el-button type="warning" style="float:left;margin-right:20px" @click="handeleOutExportExcel">导出</el-button>
      <!-- <el-button>添加</el-button> -->
    </el-row>
    <div class="table-div">
      <el-table
        :data="categoryList"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <template slot="empty">
          <p>{{ dataText }}</p>
        </template>
        <el-table-column prop="id" label="id" sortable align="center" />
        <el-table-column prop="name" label="种类名" align="center" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="showUpdateDialog(scope.$index, scope.row)">编辑</el-button>
            <el-button disabled size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 种类信息修改框 -->
    <el-dialog title="编辑图书种类" :visible.sync="dialogVisible" :before-close="handleBeforeClose">
      <el-form ref="updateForm" :model="updateForm" label-position="top" :rules="updateRules">
        <el-row>
          <el-col :span="2">
            <el-form-item label="ID" :label-width="formLableWidth">
              <el-input v-model="updateForm.id" disabled autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="种类名称" :label-width="formLableWidth" prop="name">
              <el-input v-model="updateForm.name" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancelUpdate">取  消</el-button>
        <el-button type="primary" @click="handleUpdateCommit">确定<i class="el-icon-upload el-icon--right" /></el-button>
      </span>
    </el-dialog>

    <!-- 添加图书框 -->
    <el-dialog title="添加图书种类" :visible.sync="dialogAddVisible" :before-close="handleBeforeClose">
      <el-form ref="addForm" :model="addForm" label-position="top" :rules="updateRules">
        <el-row>
          <el-col :span="11" :offset="1">
            <el-form-item label="种类名称" :label-width="formLableWidth" prop="name">
              <el-input v-model="addForm.name" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancelUpdate">取  消</el-button>
        <el-button type="primary" @click="handleAddCommit">确定<i class="el-icon-upload el-icon--right" /></el-button>
      </span>
    </el-dialog>

    <div class="block">
      <el-pagination
        :current-page.sync="getCategoryForm.current"
        :page-size="getCategoryForm.size"
        layout="prev, pager, next, jumper"
        :total="getCategoryForm.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>

</template>

<script>
import { getCategory, getCategoryDetailById, updateCategory, deleteCategory, addCategory } from '@/utils/book'
import { outExportExcel } from '@/api/exportData.js'
export default {
  data() {
    return {
      categoryList: [],
      // categoryDetail: {
      //   id: '',
      //   name: ''
      // },
      // 查询结果是否有值
      hasData: false,
      dataText: '',
      // 被选中的订单数组,有handleSelectionChange处理
      selectionBooksId: [],
      // dialog的显示消失控制
      dialogVisible: false,
      dialogAddVisible: false,
      dialogBookForm: null,
      formLableWidth: '120px',
      currentCategoryId: '',
      getCategoryForm: {
        current: 1,
        size: 10,
        cId: '',
        orderType: 0,
        total: null
      },
      updateForm: {
        id: '',
        name: ''
      }, addForm: {
        id: '',
        name: ''
      },
      updateRules: { name: [{ required: true, trigger: 'blur', message: '请输入种类名称' }] },
      MvcResult: {
        message: '',
        code: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取所有category
    getList() {
      getCategory(this.getCategoryForm).then(res => {
        // console.log(res)
        if (res.object.records && res.object.records.length > 0) {
          this.hasData = true
        } else {
          // this.$message('暂无订单数据')
          this.dataText = '暂无数据'
        }
        // this.dialogAddVisible = false
        // this.dialogVisible = false
        this.categoryList = res.object.records
        this.getCategoryForm.total = res.object.total
      })
    },
    // 选择框改变
    handleSelectionChange(val) {
      // this.multipleSelection = val
      const arr = []
      val.forEach(element => {
        arr.push(element.id)
      })
      this.selectionBooksId = arr
    },
    // 展开修改dialog
    showUpdateDialog(scopeIndex, scopeRow) {
      // this.updateForm = scopeRow
      this.getCategoryById(scopeRow.id)
      this.dialogVisible = true
      // this.getCategoryById(this.updateForm.id)
    },
    getCategoryById(id) {
      getCategoryDetailById(id).then(res => {
        // this.categoryDetail = res.object //如果用这一条则修改框里的参数会影响List展示的内容
        this.updateForm = res.object
      })
    }, showAddDialog() {
      this.dialogAddVisible = true
    },
    // 关闭之前的钩子
    handleBeforeClose() {
      // console.log('关闭llll')
      // 表单重置
      // this.$refs.updateFrom.resetFields()
      this.dialogVisible = false
      this.dialogAddVisible = false
      // this.setUpdateForm()
      // console.log(this.updateForm)
    },
    // 此方法有什么作用？？
    // setUpdateForm() {
    //   this.updateForm.name = this.categoryDetail.name
    // },
    // 取消更新
    handleCancelUpdate() {
      this.dialogVisible = false
      this.dialogAddVisible = false
    },
    // 提交更新
    handleUpdateCommit() {
      this.$refs['updateForm'].validate((valid) => {
        if (valid) {
          this.doUpdate()
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    doUpdate() {
      // console.log(this.updateForm)
      updateCategory(this.updateForm).then(res => {
        // this.$message.success('更新种类成功')
        // this.dialogVisible = false
        // this.getList()
        if (res.code === 200) {
          this.$message.success(res.message)
        }
        this.dialogVisible = false
        this.getList()
      }).catch(error => {
        console.log(error)
      })
    },
    // 删除种类
    handleDelete(scopeIndex, scopeRow) {
      this.doDelete(scopeRow.id)
    },
    doDelete(id) {
      deleteCategory(id).then(res => {
        this.$message.success('删除成功')
        this.getList()
      }).catch(error => {
        console.log(error)
      })
    },
    handleAddCommit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.doAdd(this.addForm)
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    doAdd(addForm) {
      this.addForm.name = this.addForm.name.trim()
      addCategory(addForm).then(res => {
        // console.log(res.code)
        if (res.code === 200) {
          this.$message.success(res.message)
        }
        this.dialogAddVisible = false
        this.getList()
      }).catch(error => {
        console.log(error)
      })
    },
    handleSizeChange() {

    },
    handleCurrentChange(val) {
      this.getCategoryForm.current = val
      getCategory(this.getCategoryForm).then(res => {
        if (res.object.records && res.object.records.length > 0) {
          this.categoryHasData = true
        } else {
          // this.$message('暂无订单数据')
          this.dataText = '暂无数据'
        }
        this.categoryList = res.object.records
        this.getCategoryForm.total = res.object.total
      })
    },
    handeleOutExportExcel() {
      const tableHeader = ['ID', '种类名']
      const tableKey = ['id', 'name']
      outExportExcel(
        tableHeader,
        tableKey,
        this.categoryList
      )
    }
  }
}
</script>

<style scoped lang="scss">
.right{
    margin-right: 400px;
}
.right1{
  margin-left: 500px;
}
.block {
  margin-top: 20px;
  text-align: center;
}
.table-div{
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 80px;
}

</style>
